#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
通信管理器启用脚本
用于管理不同版本的通信管理器的启用和切换
"""

import os
import shutil
import sys
from pathlib import Path

def get_core_path():
    """获取core目录路径"""
    return Path(__file__).parent / "src" / "core"

def list_communication_managers():
    """列出所有可用的通信管理器版本"""
    core_path = get_core_path()
    managers = []
    
    for file in core_path.glob("communication_manager*.py"):
        if file.name != "__init__.py":
            managers.append(file.name)
    
    return sorted(managers)

def get_current_manager():
    """获取当前启用的通信管理器"""
    core_path = get_core_path()
    current_file = core_path / "communication_manager.py"
    
    if current_file.exists():
        # 检查是否是某个特定版本
        with open(current_file, 'r', encoding='utf-8') as f:
            content = f.read()
            if "DataProcessingThread" in content:
                return "communication_manager.py (重构版本)"
            else:
                return "communication_manager.py (原始版本)"
    else:
        return "未找到"

def backup_current_manager():
    """备份当前的通信管理器"""
    core_path = get_core_path()
    current_file = core_path / "communication_manager.py"
    backup_file = core_path / f"communication_manager_backup_{int(os.path.getmtime(current_file))}.py"
    
    if current_file.exists():
        shutil.copy2(current_file, backup_file)
        print(f"✅ 已备份当前版本到: {backup_file.name}")
        return backup_file.name
    else:
        print("⚠️ 当前没有启用的通信管理器")
        return None

def enable_manager(manager_name):
    """启用指定的通信管理器"""
    core_path = get_core_path()
    source_file = core_path / manager_name
    target_file = core_path / "communication_manager.py"
    
    if not source_file.exists():
        print(f"❌ 源文件不存在: {manager_name}")
        return False
    
    try:
        # 先备份当前版本
        if target_file.exists():
            backup_current_manager()
        
        # 复制新版本
        shutil.copy2(source_file, target_file)
        print(f"✅ 已启用: {manager_name}")
        return True
        
    except Exception as e:
        print(f"❌ 启用失败: {e}")
        return False

def test_manager():
    """测试当前启用的通信管理器"""
    try:
        sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        from core.communication_manager import CommunicationManager
        
        # 创建实例测试
        comm_manager = CommunicationManager()
        print("✅ 通信管理器导入和实例化成功")
        
        # 检查是否有新功能
        if hasattr(comm_manager, 'data_processing_thread'):
            print("✅ 检测到重构后的新功能:")
            print("   - 独立数据处理线程")
            print("   - 队列缓冲机制")
            print("   - 异步信号通信")
        else:
            print("ℹ️ 当前使用的是原始版本")
        
        return True
        
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        return False

def show_status():
    """显示当前状态"""
    print("\n📊 通信管理器状态:")
    print("=" * 50)
    
    # 当前启用的版本
    current = get_current_manager()
    print(f"当前启用: {current}")
    
    # 可用版本列表
    available = list_communication_managers()
    print(f"\n可用版本:")
    for i, manager in enumerate(available, 1):
        if manager == "communication_manager.py":
            print(f"  {i}. {manager} (当前启用)")
        else:
            print(f"  {i}. {manager}")
    
    print("=" * 50)

def main():
    """主函数"""
    print("🔧 通信管理器启用工具")
    print("=" * 50)
    
    if len(sys.argv) < 2:
        show_status()
        print("\n使用方法:")
        print("  python enable_communication_manager.py status          # 显示状态")
        print("  python enable_communication_manager.py test            # 测试当前版本")
        print("  python enable_communication_manager.py enable <版本>   # 启用指定版本")
        print("  python enable_communication_manager.py backup          # 备份当前版本")
        return
    
    command = sys.argv[1].lower()
    
    if command == "status":
        show_status()
        
    elif command == "test":
        print("🧪 测试当前通信管理器...")
        test_manager()
        
    elif command == "enable":
        if len(sys.argv) < 3:
            print("❌ 请指定要启用的版本")
            return
        
        manager_name = sys.argv[2]
        print(f"🚀 正在启用: {manager_name}")
        enable_manager(manager_name)
        
    elif command == "backup":
        print("💾 备份当前版本...")
        backup_current_manager()
        
    else:
        print(f"❌ 未知命令: {command}")
        print("可用命令: status, test, enable, backup")

if __name__ == "__main__":
    main()
